import logging

import pytest


class Test:

    @pytest.mark.parametrize('setup_teardown', [None], indirect=True)
    def test(self, setup_teardown, device, factory_reset):
        logging.info('步骤1、长按桌面应用添加到dock栏')
        device.refresh_layout()
        badges0 = device.get_elements_by_type('Badge')
        first_badge0 = badges0[0]
        fx0, fy0 = device.center_of_element(first_badge0)
        dock_badges0 = self.get_badges_by_pos(device, badges0)
        dock_x, dock_y = 628, 1145
        device.drag(fx0, fy0, dock_x, dock_y)
        logging.info('预期结果1：相机应用成功从桌面移动到dock栏')
        device.refresh_layout()
        badges1 = device.get_elements_by_type('Badge')
        dock_badges1 = self.get_badges_by_pos(device, badges1)
        assert len(dock_badges1) > len(dock_badges0), 'dock栏图标数量变化：{}->{}'.format(len(dock_badges0), len(dock_badges1))

        logging.info('步骤2：长按dock栏应用移动到桌面')
        last_badge = badges1[-1]
        lx, ly = device.center_of_element(last_badge)
        device.drag(lx, ly, fx0, fy0)
        logging.info('预期结果2：应用成功从dock栏移动到桌面')
        device.refresh_layout()
        badges2 = device.get_elements_by_type('Badge')
        dock_badges2 = self.get_badges_by_pos(device, badges2)
        assert len(dock_badges2) < len(dock_badges1), 'dock栏图标数量变化：{}->{}'.format(len(dock_badges1), len(dock_badges2))

        logging.info('步骤3：长按拖动到本页任意处')
        new_x, new_y = fx0, fy0 + 141 * 3
        device.drag(fx0, fy0, new_x, new_y)
        logging.info('预期结果3：可拖动到本页任意位置')
        device.refresh_layout()
        badges3 = device.get_elements_by_type('Badge')
        moved_badge = None
        for icon in badges3:
            if abs(device.center_of_element(icon)[1] - new_y) <= 70:
                moved_badge = icon
                break

        assert moved_badge, '拖动可能不成功，请查看截图或者手工测试'

        logging.info('步骤4：长按拖动到下页')
        device.drag(new_x, new_y, 690, new_y)
        device.refresh_layout()
        logging.info('预期结果4：可拖动到下页')
        badges4 = device.get_elements_by_type('Badge')
        assert len(badges4) < 6, '拖动到下页失败，图标数量不对'

    @staticmethod
    def get_badges_by_pos(device, badge_list, at_dock=True):
        blist = []
        for b in badge_list:
            bx, by = device.center_of_element(b)
            # dock栏的图标
            if at_dock and by > 1100:
                blist.append(b)
            # 桌面图标
            elif not at_dock and by < 1100:
                blist.append(b)
        return blist
